//
//  LoginViewController.m
//  ZhangJiangJun
//
//  Created by FENGYL on 2017/1/12.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "LoginViewController.h"
#import "UIView+XL.h"
#import "UserModel.h"
#import "NetworkCommand.h"
#import "MainNavigationController.h"
#import "UserModel.h"

#import <AFNetworking.h>
#import <MBProgressHUD.h>

#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface LoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *rememberPasswordButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (strong, nonatomic) UserModel * userModel;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    //背景颜色
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"zjj_j_d"]]];

    [self setUpUI];
    
    self.userNameTextField.delegate = self;
    self.passwordTextField.delegate = self;
    
}

#pragma mark 设置UI
-(void)setUpUI{
    
    //用户名图片
    UIView * userView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.userNameTextField.height, self.userNameTextField.height)];
    
    UIImageView * userImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"zjj_lodng_ure"]];
    
    userImageView.frame = CGRectMake(5, 5, self.userNameTextField.height - 10, self.userNameTextField.height - 10);
    
    [userView addSubview:userImageView];
    
    self.userNameTextField.leftView = userView;
    
    self.userNameTextField.leftViewMode = UITextFieldViewModeAlways;
    
    //用户名placeholder
    self.userNameTextField.placeholder = NSLocalizedString(LOCALIZABLE_ACCOUNT_PLACEHOLDER, nil);
    
    
    //密码图片
    UIView * pwView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.passwordTextField.height, self.passwordTextField.height)];
    
    UIImageView * pwImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"zjj_lodng_key"]];
    
    pwImageView.frame = CGRectMake(5, 5, self.passwordTextField.height - 10, self.passwordTextField.height - 10);
    
    [pwView addSubview:pwImageView];
    
    
    self.passwordTextField.leftView = pwView;
    
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    
    //密码placeholder
    self.passwordTextField.placeholder = NSLocalizedString(LOCALIZABLE_PASSWORD_PLACEHOLDER, nil);
    
    
    //记住密码按钮文字
    [self.rememberPasswordButton setTitle:NSLocalizedString(LOCALIZABLE_REMEMBER_PASSWORD, nil) forState:UIControlStateNormal];
    
    //登录按钮文字
    [self.loginButton setTitle:NSLocalizedString(LOCALIZABLE_LOGIN, nil) forState:UIControlStateNormal];
    
    //限制输入长度
    [self.userNameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    //是否记住密码
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    BOOL isRememberPassword = [userDefaults boolForKey:UD_REMEMBER_PASSWORD];
    
    self.rememberPasswordButton.selected = isRememberPassword;
    
    //记住账号
    [self.userNameTextField setText:[userDefaults objectForKey:UD_USERNAME]];
    
    //密码
    if (isRememberPassword) {
        
        [self.passwordTextField setText:[userDefaults objectForKey:UD_PASSWORD]];
        
        //自动登录
        [self touchLoginButton:nil];
        
    }
}

#pragma mark 记住密码
- (IBAction)rememberPasswordOrNot:(id)sender {
    
    self.rememberPasswordButton.selected = !self.rememberPasswordButton.selected;
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setBool:self.rememberPasswordButton.selected forKey:UD_REMEMBER_PASSWORD];
    
}

#pragma mark 登录按钮
- (IBAction)touchLoginButton:(id)sender {
    
    if (!(self.userNameTextField.text.length >= 6 && self.passwordTextField.text.length >= 6)) {
        
        MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [hud.label setText:NSLocalizedString(LOCALIZABLE_LOGIN_WARNING, nil)];
        
        hud.mode = MBProgressHUDModeCustomView;
        
        hud.removeFromSuperViewOnHide = YES;
        
        [hud hideAnimated:YES afterDelay:0.5];
        
        return;
        
    }
    
    //loading hud
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [hud.label setText:NSLocalizedString(LOCALIZABLE_LOADING, nil)];
    
    hud.mode = MBProgressHUDModeIndeterminate;
    
    hud.removeFromSuperViewOnHide = YES;
    
    
    [NetworkCommand userLoginUserName:self.userNameTextField.text password:self.passwordTextField.text success:^{
        
    
        //记住密码
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        
        [userDefaults setBool:self.rememberPasswordButton.selected forKey:UD_REMEMBER_PASSWORD];
        
        [userDefaults setObject:self.userNameTextField.text forKey:UD_USERNAME];
        
        if (self.rememberPasswordButton.selected) {
            
            [userDefaults setObject:self.passwordTextField.text forKey:UD_PASSWORD];
            
        }else{
            
            [userDefaults setObject:nil forKey:UD_PASSWORD];
            
        }
        
        
        [hud hideAnimated:YES];
        
        //跳转
        
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        MainNavigationController * mainNavigationController = [storyboard instantiateViewControllerWithIdentifier:@"MainNavigationController"];
        
        [self presentViewController:mainNavigationController animated:YES completion:nil];
        
    } failure:^{
        
        [hud.label setText:NSLocalizedString(LOCALIZABLE_LOGIN_FAILED, nil)];
        
        hud.mode = MBProgressHUDModeCustomView;
        
        [hud hideAnimated:YES afterDelay:0.5];
        
    }];
    
}

#pragma mark 获取GUID
- (NSString *)getUniqueStrByUUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    //get the string representation of the UUID
    
    NSString    *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}

#pragma mark 限制textfield输入类型
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    
    return [string isEqualToString:filtered];
    
}


#pragma mark 限制输入长度
- (void)textFieldDidChange:(UITextField *)textField
{
//    if (self.userNameTextField.text.length >= 6 && self.passwordTextField.text.length >= 6) {
//        
//        self.loginButton.enabled = YES;
//        
//    }else{
//        
//        self.loginButton.enabled = NO;
//        
//    }
    
    if (textField.text.length > 32) {
        
        textField.text = [textField.text substringToIndex:32];
        
    }
    
    
}



//#pragma mark 收起键盘
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//
//    [self.userNameTextField resignFirstResponder];
//    [self.passwordTextField resignFirstResponder];
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
